''' 用户登录管理 '''
import sys,traceback,logging,datetime
import pymysql
from dbutils.pooled_db import PooledDB 
from utils.db_config import mysqlInfo
from utils.tokenutil import TokenUtil
from utils.didiutils import Encrypt,generate_verification_code
import math

logger = logging.getLogger('app')

# 创建数据库连接
def connect_db():
    pool=PooledDB(creator=pymysql,mincached=2, maxcached=5,maxshared=3, maxconnections=6, blocking=True,host=mysqlInfo['host'],port=mysqlInfo['port'],
        user=mysqlInfo['user'],password=mysqlInfo['password'],database=mysqlInfo['database'],charset=mysqlInfo['charset'],cursorclass=pymysql.cursors.DictCursor)
    return pool.connection()


'''
admin 登录页面(组)
'''
# 账号密码登录
def login(param):
    conn = connect_db()
    cur = conn.cursor()
    result = {}
    rowdict = {}
    try:
        print(param['user_id'])
        sql = " select password, salt, is_admin, status,user_id,user_name,phone From user Where user_id=%s "
        cur.execute(sql, (param['user_id'],))
        for row in cur.fetchall():
            rowdict['password'] = row['password']
            rowdict['salt'] = row['salt']
            rowdict['is_admin'] = row['is_admin']
            rowdict['status'] = row['status']
            rowdict['userid'] = row['user_id']
            rowdict['username'] = row['user_name']
            rowdict['phone'] = row['phone']
        if rowdict:
            if rowdict['salt'] is not None:
                enc = Encrypt(rowdict['salt'])
                j_pwd = enc.decrypt(rowdict['password'])
                if j_pwd != param['password']:
                    result['message'] = '密码错误'
                    result['code'] = 0
                    result['result'] = 'ng'
                else:
                    payload = TokenUtil.getPayload(param['user_id'],rowdict['phone'])
                    token = TokenUtil.encode(payload)
                    rowdict['token'] = token
                    result['code'] = 200
                    result['result'] = rowdict
                    result['message'] = 'ok'
            else:
                result['message'] = '账号错误'
                result['code'] = 0
                result['result'] = 'ng'
            if rowdict['status'] == '1':
                result['message'] = '该用户已禁用，请联系管理员'
                result['code'] = 0
                result['result'] = 'ng'
        else:
            result['message'] = '账号不存在'
            result['code'] = 0
            result['result'] = 'ng'
    except:
        logger.error(sys.exc_info())
        logger.error(traceback.format_exc())
        conn.rollback()
    finally:
        cur.close()
        conn.close()
        return result



'''
admin系统用户管理页面（组)
'''
# 获取用户信息列表
def getuserlist(param):
    conn = connect_db()
    cur = conn.cursor()
    result = {}
    reclist = []
    pageSize = param['pageSize']
    pageCurrent = param['pageCurrent']
    try:
        if param:
            sql = r" select password, salt, is_admin, status, user_id, user_name, id, DATE_FORMAT(update_time, '%Y-%m-%d %H:%i:%s') AS update_time, phone, email from user where 1=1 "
            if 'name' in param.keys():
                if param['name'] is not None and param['name'] != '':
                    sql += " and user_name like '%" + param['name'] + "%' "
            if 'selectRole' in param.keys():
                if param['selectRole'] is not None and param['selectRole'] != '':
                    sql += " and is_admin = '" + param['selectRole'] + "' "
            if 'selectStatus' in param.keys():
                if param['selectStatus'] is not None and param['selectStatus'] != '':
                    sql += " and status = '" + param['selectStatus'] + "' "
            sql += " order by update_time desc "
        else:
            sql = "select password, salt, is_admin, status, user_id, user_name, id, DATE_FORMAT(update_time, '%Y-%m-%d %H:%i:%s') AS update_time, phone, email from user order by update_time desc "

        cur.execute(sql)
        
        fetchall = cur.fetchall()
        itemCount = len(fetchall)
        pageCount = math.ceil(itemCount / pageSize)
        start_idx = (pageCurrent - 1) * pageSize
        end_idx = start_idx + pageSize
        pageData = fetchall[start_idx:min(end_idx, itemCount)]
        for row in pageData:
            rowdict = {}
            j_pwd = ''
            try:
                enc = Encrypt(row['salt'])
                j_pwd = enc.decrypt(row['password'])
            except:
                pass
            rowdict['password'] = j_pwd
            rowdict['salt'] = row['salt']
            rowdict['role'] = row['is_admin']
            rowdict['status'] = row['status']
            rowdict['userid'] = row['user_id']
            rowdict['username'] = row['user_name']
            rowdict['id'] = row['id']
            rowdict['updatetime'] = row['update_time']
            rowdict['phone'] = row['phone']
            rowdict['email'] = row['email']
            reclist.append(rowdict)
        data = {}
        data['list'] = reclist
        data['itemCount'] = 48
        data['page'] = pageCurrent
        data['pageSize'] = pageSize
        data['pageCount'] = pageCount
        data['itemCount'] = itemCount
        result['code'] = 200
        result['result'] = data
        result['message'] = 'ok'

    except:
        logger.error(sys.exc_info())
        logger.error(traceback.format_exc())
        conn.rollback()
    finally:
        cur.close()
        conn.close()
        return result

# 创建用户
def createuser(param):
    conn = connect_db()
    cur = conn.cursor()
    result = {}
    rowdict = {}
    try:
        sql = " select user_id from user where user_id = %s "
        cur.execute(sql, (param['userid']))
        for row in cur.fetchall():
            result['message'] = '登录用户ID已存在'
            result['code'] = 0
            result['result'] = 'ng'
            return result
        salt = generate_verification_code(16)
        enc = Encrypt(salt)
        pwd = enc.encrypt(param['password'])
        sql = " insert into user(user_id,user_name,password,salt,is_admin,phone,email,status,update_time) value(%s,%s,%s,%s,%s,%s,%s,%s,%s) "
        cur.execute(sql, (
        param['userid'], param['username'], pwd, salt, param['role'], param['phone'], param['email'], param['status'],
        datetime.datetime.now()))

        result['code'] = 200
        result['result'] = 'ok'
        result['message'] = ''
        conn.commit()
    except:
        logger.error(sys.exc_info())
        logger.error(traceback.format_exc())
        conn.rollback()
    finally:
        cur.close()
        conn.close()
        return result

# 更新用户
def updateuser(param):
    conn = connect_db()
    cur = conn.cursor()
    result = {}
    rowdict = {}
    try:
        salt = generate_verification_code(16)
        enc = Encrypt(salt)
        pwd = enc.encrypt(param['password'])
        sql = " update user set password=%s,salt=%s,is_admin=%s,phone=%s,email=%s,status=%s,update_time=%s where id = %s "
        cur.execute(sql, (
        pwd, salt, param['role'], param['phone'], param['email'], param['status'], datetime.datetime.now(),
        param['id']))

        result['code'] = 200
        result['result'] = 'ok'
        result['message'] = ''
        conn.commit()
    except:
        logger.error(sys.exc_info())
        logger.error(traceback.format_exc())
        conn.rollback()
    finally:
        cur.close()
        conn.close()
        return result

# 删除用户
def deleteuser(params):
    conn = connect_db()
    cur = conn.cursor()
    result = {}
    try:
        sql = " delete from user where id = %s "
        cur.execute(sql, (params['id']))
        result['code'] = 200
        result['result'] = 'ok'
        result['message'] = ''
        conn.commit()
    except:
        logger.error(sys.exc_info())
        logger.error(traceback.format_exc())
        conn.rollback()
    finally:
        cur.close()
        conn.close()
        return result
